package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.EditSpinner;
import com.chcit.custom.view.text.AutofitTextView;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.contains.HttpMethodContains;
import com.chcit.mobile.app.utils.DialogUtil;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.model.entity.Locator;
import com.chcit.mobile.mvp.model.entity.MonitorCode;
import com.chcit.mobile.mvp.model.entity.Reason;
import com.chcit.mobile.mvp.model.entity.ReceiveBean;
import com.chcit.mobile.mvp.ui.adapter.MonitorCodeAdapter;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.chcit.mobile.di.component.DaggerReceiveDetailComponent;
import com.chcit.mobile.di.module.ReceiveDetailModule;
import com.chcit.mobile.mvp.contract.ReceiveDetailContract;
import com.chcit.mobile.mvp.presenter.ReceiveDetailPresenter;

import com.chcit.mobile.R;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ReceiveDetailFragment extends ScanFragment<ReceiveDetailPresenter> implements ReceiveDetailContract.View {

    @BindView(R.id.tv_purchase_detail_index)
    TextView tvPurchaseDetailIndex;
    /*  @BindView(R.id.tv_purchase_detail_productName)
      TextView tvPurchaseDetailProduct;*/
    @BindView(R.id.tv_purchase_detail_productSpec)
    TextView tvPurchaseDetailProductSpec;
    @BindView(R.id.tv_purchase_detail_manufacturer)
    TextView tvPurchaseDetailManufacturer;
    @BindView(R.id.tv_purchase_detail_productCode)
    TextView tvPurchaseDetailProductCode;
    @BindView(R.id.tv_purchase_detail_uom)
    TextView tvPurchaseDetailUom;
    @BindView(R.id.tv_purchase_detail_lot)
    TextView tvPurchaseDetailLot;
    @BindView(R.id.tv_purchase_detail_guaranteeDate)
    TextView tvPurchaseDetailGuaranteeDate;
    @BindView(R.id.tv_purchase_detail_pricePO)
    SuperTextView tvPurchaseDetailPricePO;
    @BindView(R.id.tv_purchase_detail_productName)
    AutofitTextView tvProductName;
    @BindView(R.id.tv_purchase_detail_priceOrder)
    SuperTextView tvPurchaseDetailPriceOrder;
    @BindView(R.id.tv_purchase_detail_vendor)
    TextView tvPurchaseDetailVendor;
    @BindView(R.id.tv_purchase_detail_qtyArrived)
    TextView tvPurchaseDetailQtyArrived;
    @BindView(R.id.tv_purchase_detail_inventory)
    TextView tvPackageQty;//大包装数
    @BindView(R.id.tv_purchase_detail_qtyConfirmed)
    AppCompatEditText etPurchaseDetailQtyConfirmed;
    @BindView(R.id.et_purchase_detail_qtyRejected)
    AppCompatEditText etPurchaseDetailQtyRejected;
    @BindView(R.id.spinner_purchase_detail_rejectReason)
    MaterialSpinner spinnerPurchaseDetailRejectReason;
    @BindView(R.id.spinner_purchase_detail_locator)
    EditSpinner spinnerPurchaseDetailLocator;
    @BindView(R.id.et_purchase_detail_invoiceNo)
    EditText etPurchaseDetailInvoiceNo;
    @BindView(R.id.bt_purchase_detail_cancel)
    Button btPurchaseDetailCancel;
    @BindView(R.id.bt_purchase_detail_ok)
    Button btPurchaseDetailOk;
    @BindView(R.id.buttom_bar_group)
    LinearLayout buttomBarGroup;
    @BindView(R.id.tv_purchase_detail_unit)
    TextView tvUnit;
    @BindView(R.id.tv_purchase_detail_odd)
    TextView tvOdd;
    @Inject
    List<Reason> reasons;
    @Inject
    List<Locator> locators;
    private ReceiveBean receiveBean;

    private Locator locator;//设置的货位
    private String barcodeData;
    public static ReceiveDetailFragment newInstance(ReceiveBean receiveBean) {
        ReceiveDetailFragment fragment = new ReceiveDetailFragment();
        fragment.receiveBean = receiveBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveDetailModule(new ReceiveDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_receive_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle(receiveBean.getASNTypeName());
        mCommonToolbar.getViewByTag(1).setOnClickListener(l->{
            pop();
        });
        setData();
        initSpinner();

    }

    private void initSpinner() {
        mPresenter.getReasons(spinnerPurchaseDetailRejectReason);

        spinnerPurchaseDetailLocator.setImageOnClickListener(new View.OnClickListener() {
            int i=0;
            @Override
            public void onClick(View v) {
                if(i==0){
                    i++;
                    JSONObject data = new JSONObject();
                    data.put("productId", receiveBean.getProductId());
                    data.put("showStorageLoc", "");
                    mPresenter.getLocators(data,list->{
                        locators = list;
                        spinnerPurchaseDetailLocator.setItemData(locators);
                        spinnerPurchaseDetailLocator.setOnItemChageClickListener((parent, view, position, id) -> {
                            if(position>=0){
                                locator = locators.get(position);
                            }
                        });
                        v.performClick();

                    });
                }
            }
        });
        JSONObject data = new JSONObject();
        data.put("productId", receiveBean.getProductId());
        data.put("showStorageLoc", "Y");
        mPresenter.getLocators(data,list->{
            if(list.size()>0){
                locator = list.get(0);
                spinnerPurchaseDetailLocator.setText(locator.getName());
            }

        });

    }

    private void setData() {
        if(receiveBean.getPriceActual().compareTo(receiveBean.getPriceActual())!=0){
            tvPurchaseDetailPricePO.setCenterTextColor(getResources().getColor(R.color.Red));
            tvPurchaseDetailPriceOrder.setCenterTextColor(getResources().getColor(R.color.Red));
        }
        tvPurchaseDetailIndex.setText(receiveBean.getAsnNo());
        tvProductName.setText(receiveBean.getProductName());
        tvPurchaseDetailProductSpec.setText(receiveBean.getProductSpec());
        tvPurchaseDetailManufacturer.setText(receiveBean.getManufacturer());
        tvPurchaseDetailProductCode.setText(receiveBean.getProductCode());//不清楚 ？
        tvPurchaseDetailUom.setText(receiveBean.getUomName());
        tvPurchaseDetailLot.setText(receiveBean.getLot());
        tvPurchaseDetailGuaranteeDate.setText(receiveBean.getGuaranteeDate());
        tvPackageQty.setText(receiveBean.getLPackageQty().intValue()+"");
       // tvPurchaseDetailPricePO.setCenterString((receiveBean.getPriceActual()+"元"));//?
       // tvPurchaseDetailPriceOrder.setCenterString((receiveBean.getPriceActual()+"元"));
        tvPurchaseDetailVendor.setText(receiveBean.getBpartnerName());
        tvPurchaseDetailQtyArrived.setText((receiveBean.getQtyArrived().intValue()+""));
        etPurchaseDetailQtyConfirmed.setText((receiveBean.getQtyArrived().intValue()+""));
        etPurchaseDetailQtyRejected.setText("0");
        //tvUnit.setText((receiveBean.getQtyArrived()+"包/"+receiveBean.getUnitQty()+receiveBean.getUomName()));
        //tvOdd.setText((receiveBean.getUnitPackageCount()+"包/"+(receiveBean.getOddQty()==null?"0":receiveBean.getOddQty())+receiveBean.getUomName()));
        // spinnerPurchaseDetailQtyRejected.setText(receiveBean.getUomName());
        // spinnerPurchaseDetailRejectReason.setText(receiveBean.getUomName());
        // etPurchaseDetailLocator.setText(receiveBean.g);
        //etPurchaseDetailInvoiceNo.setText(receiveBean.getTaxInvoiceNo());
        etPurchaseDetailQtyConfirmed.addTextChangedListener(new TextWatcher() {
            String beforeText ;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s,beforeText,etPurchaseDetailQtyConfirmed,etPurchaseDetailQtyRejected);
            }
        });

        etPurchaseDetailQtyRejected.addTextChangedListener(new TextWatcher() {
            String beforeText ;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s,beforeText,etPurchaseDetailQtyRejected,etPurchaseDetailQtyConfirmed);
            }
        });
    }

    private void doAfterTextChanged(Editable s,String beforeText,EditText nowEdit,EditText newText) {
        String data = s.toString();
        if(nowEdit.hasFocus()&&!data.equals(beforeText)){

            try {
                BigDecimal received = new BigDecimal(0);
                if(!data.isEmpty()){
                    received =new BigDecimal(data);
                }
                BigDecimal number = receiveBean.getQtyArrived().subtract(received);
                if(number.intValue() <0){
                    DialogUtil.showMsgDialog(getContext(),"提示","实收数量必须小于等于到货数量！");
                    nowEdit.setText(beforeText);
                    return;
                }
                newText.setText((number+""));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

        if(isScanSupervision){
            etSupervision.setText(barcodeData);
            addBindData();
        }else{
            spinnerPurchaseDetailLocator.setText(barcodeData);
            assert mPresenter != null;
            mPresenter.getLocatorId(barcodeData);
        }
    }

    @OnClick({R.id.bt_purchase_detail_cancel, R.id.bt_purchase_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_purchase_detail_cancel:
                isScanSupervision = true;
           /*     if(shipmentBean.getSupervisionCodes()!=null){
                    monitorCodeAdapter.getData().addAll(monitorCodes);
                }*/
                mPresenter.getMonitorCodes(receiveBean.getAsnLineId(),list ->{
                    monitorCodes.clear();
                    monitorCodes.addAll(list);
                    monitorCodeAdapter.notifyDataSetChanged();
                });
                buder.show();
                break;
            case R.id.bt_purchase_detail_ok:
                //  DialogUtil.showMsgDialog(getContext(),"",receiveBean.toString());
                if(spinnerPurchaseDetailLocator.getText().isEmpty()){
                    DialogUtil.showMsgDialog(getContext(),"提示","请输入货位！");
                    return;
                }
                int locatorId = 0;
                if(locator == null){
                    mPresenter.getLocatorId(spinnerPurchaseDetailLocator.getText());
                }else{
                    locatorId = locator.getLocatorId();
                    doConfirm(locatorId);

                }

                break;
        }
    }

    private void doConfirm(int locatorId) {
        int asnId = receiveBean.getAsnId();
        int asnLineId = receiveBean.getAsnLineId();
        String qtyReceived = etPurchaseDetailQtyConfirmed.getText().toString();
        String rejectSty =etPurchaseDetailQtyRejected.getText().toString();
        int rejectQty = 0;
        if(!rejectSty.isEmpty()){
            rejectQty = Integer.parseInt(rejectSty);
        }
        String rejectReason = reasons.get(spinnerPurchaseDetailRejectReason.getSelectedIndex()).getValue();
        if(rejectQty>0&& rejectReason == null){
            DialogUtil.showMsgDialog(getContext(),"提示","请选择拒收原因");
            return ;
        }
        JSONObject data = new JSONObject();
        data.put("asnId", asnId);//
        data.put("asnLineId", asnLineId);
        data.put("rejectQty", rejectQty);
        data.put("locatorId", locatorId);
        data.put("qtyReceived", qtyReceived);
        data.put("rejectReason", rejectReason);
//        data.put("asnLineID", asnLineId);
//        data.put("rejectqty", rejectQty);
//        data.put("locatorID", locatorId);
//        data.put("storageStatus",receiveBean.getStorageStatus());
//        data.put("qty", qtyReceived);
//        data.put("rejectReason", rejectReason);
        mPresenter.doConfirm(data,()->{
            setFragmentResult(RESULT_OK,null);
            pop();
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        if("SR".equals(receiveBean.getASNType())){
            initScanDialog();
        }else{
            btPurchaseDetailCancel.setEnabled(false);
        }
    }

    private MaterialDialog buder;
    private SuperEditText etSupervision;
    private MonitorCodeAdapter monitorCodeAdapter;
    private List<MonitorCode> monitorCodes = new ArrayList<>();
    boolean isScanSupervision = false;//是否是扫描监管码
    void initScanDialog(){

        monitorCodeAdapter = new MonitorCodeAdapter(monitorCodes);
        buder = new MaterialDialog.Builder(mContext)
                .title("监管码绑定")
                .titleGravity(GravityEnum.CENTER)
                .customView(R.layout.dialog_scan_ok, true)
                .positiveText("确认")
                //.negativeText("取消")
                .autoDismiss(false)
                .onAny((dialog, which) -> {
                    isScanSupervision = false;
                    if (which == DialogAction.POSITIVE) {
                        //pickListMaId:1212,monitoringCode:['1111','1234','4444']
                        JSONArray monitoringCode = new JSONArray();
                        for(MonitorCode m :monitorCodes){
                            if(m.getId()>0){
                                monitoringCode.add(m.getCode());
                            }

                        }
                        if(monitoringCode.size()>0){
                            JSONObject data = new JSONObject();
                            data.put("asnLineId",receiveBean.getAsnLineId());
                            data.put("monitoringCode",monitoringCode);
                            mPresenter.doConfirm(HttpMethodContains.RECEIVE_CODE_CREATE,data, dialog::dismiss);
                        }

                    }else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        monitorCodeAdapter.getData().clear();
                        monitorCodeAdapter.notifyDataSetChanged();
                    }
                    //dialog.dismiss();
                })
                .build();


        //初始化Adapter
        RecyclerView recyclerView = buder.getCustomView().findViewById(R.id.rv_purchase_scan_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(monitorCodeAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(recyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            private int position = -1;
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                position = pos;
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                //{pickListMaId:1212,monitoringCode:1111}
                if(pos!=-1){
                    position = pos;
                }
                MonitorCode  m = monitorCodes.get(position);
                if(m.getId() == 0){
                    JSONObject data = new JSONObject();
                    data.put("asnLineId",receiveBean.getAsnLineId());
                    data.put("monitoringCode",m.getCode());
                    mPresenter.doConfirm(HttpMethodContains.RECEIVE_CODE_DELETE,data,()->{

                    });
                }
                //{pickListMaId:1212,monitoringCode:1111}

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        monitorCodeAdapter.enableSwipeItem();
        monitorCodeAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        monitorCodeAdapter.enableDragItem(mItemTouchHelper);
        monitorCodeAdapter.setOnItemDragListener(listener);
        recyclerView.setAdapter(monitorCodeAdapter);
        Button button = buder.getCustomView().findViewById(R.id.button_scan_clear);
        button.setOnClickListener(l->{
            monitorCodeAdapter.getData().clear();
            monitorCodeAdapter.notifyDataSetChanged();
        });
        etSupervision = buder.getCustomView().findViewById(R.id.et_receiveScanCode_list_SerNo);
        etSupervision.setOnKeyListener((v, keyCode, event) -> {

            if (keyCode == KeyEvent.KEYCODE_ENTER && !etSupervision.getText().toString().isEmpty()) {

                addBindData();
                return true;
            } else {
                return false;
            }

        });

    }
    private void addBindData() {
        barcodeData = etSupervision.getText().toString();
        MonitorCode supervisionCode  =new MonitorCode(receiveBean.getAsnLineId(),barcodeData);

        if (monitorCodeAdapter.getData().contains(supervisionCode)) {
            Toast.makeText(mContext, "绑定的数据重复！", Toast.LENGTH_LONG).show();
            return;
        }
        monitorCodeAdapter.addData(supervisionCode);

    }
}
